package com.cgycms.webdeploy.auth;

import cn.hutool.json.JSONUtil;
import com.cgycms.webdeploy.filter.SpringContextHolder;
import com.cgycms.webdeploy.storage.DeployConfig;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName : AuthLoad
 * @Description : 用户配置信息加载
 * @Author : 王力超
 * @Date: 2020-10-14 18:50
 */
@Configuration
public class AuthLoad {

    private static Logger log = LoggerFactory.getLogger(AuthLoad.class);

    public static List<UserModel> users = null;

    public static Map<String, UserModel> userMap = null;

    @Autowired
    private DeployConfig deployConfig;

    @PostConstruct
    public void init() {
        loadAuthUsers();
    }

    public  boolean loadAuthUsers() {
        try {
            Resource resource = null;
            DeployConfig config = deployConfig;
            if (config != null && !StringUtils.isEmpty(config.getAuthPath())) {
                log.info("指定位置加载用户信息:" + config.getAuthPath());
                resource = new FileSystemResource(new File(config.getAuthPath()));
            } else {
                resource = new ClassPathResource("auth.json");
                log.info("默认位置加载用户信息...");
            }
            String jsons = FileUtils.readFileToString(resource.getFile(), "UTF-8");
            users = JSONUtil.toList(JSONUtil.parseArray(jsons), UserModel.class);
            userMap = users.stream().collect(Collectors.toMap(a -> a.getUserName(), s -> s));
            log.info("加载用户信息成功~");
            return true;
        } catch (IOException e) {
            log.error("加载用户信息出错！");
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            String key = "Duplicate key";
            if (e.getMessage().contains(key)) {
                log.error("存在重复登录账号,请检查配置文件！");
            }
        }
        return false;
    }

}
